import couchdb

class ErlySocialInterface(object):
    def __init__(self, server, db_name='erlysocial'):
        self.server = couchdb.Server(server)
        self.db = self.server[db_name]

    def get_identity_urls(self, url, view_name='_view/identity/get'):
        first = set((url,))
        second = set((url,))
        for row in self.db.view(view_name, startkey=[url,0], endkey=[url,1]):
            if row.key[1] == 0:
                first.add(row.value)
            else:
                second.add(row.value)
        return list(first.intersection(second))
    
    def get_friends(self, urls, view_name='_view/friends/get'):
        first = set()
        second = set()
        for url in urls:
            for row in self.db.view(view_name, startkey=[url,0], endkey=[url,1]):
                if row.key[1] == 0:
                    first.add(row.value)
                else:
                    second.add(row.value)
        return list(first.intersection(second))
    
    def get_friends_from_url(self, url):
        return self.get_friends(self.get_identity_urls(url))